package com.sjy.project.ent.api;

import java.util.Date;
import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.sjy.framework.aspectj.lang.annotation.Log;
import com.sjy.framework.aspectj.lang.enums.BusinessType;
import com.sjy.project.ent.yearSta.domain.EntAppeal;
import com.sjy.project.ent.yearSta.domain.EntAppealLandData;
import com.sjy.project.ent.yearSta.domain.EntAppealRentInLand;
import com.sjy.project.ent.yearSta.domain.EntAppealRentOutLand;
import com.sjy.project.ent.yearSta.domain.EntKpiYearSta;
import com.sjy.project.ent.yearSta.service.IEntAppealLandDataService;
import com.sjy.project.ent.yearSta.service.IEntAppealRentInLandService;
import com.sjy.project.ent.yearSta.service.IEntAppealRentOutLandService;
import com.sjy.project.ent.yearSta.service.IEntAppealService;
import com.sjy.project.ent.yearSta.service.IEntKpiYearStaService;
import com.sjy.project.system.dept.service.IDeptService;
import com.sjy.project.system.user.domain.User;
import com.sjy.project.system.user.service.IUserService;

import cn.hutool.core.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import com.sjy.framework.web.controller.BaseController;
import com.sjy.framework.web.domain.AjaxResult;
import com.sjy.common.constant.UserContext;
import com.sjy.common.entity.SecuryUserDetail;
import com.sjy.common.enums.AppealEnum;
import com.sjy.common.result.BaseResponse;
import com.sjy.common.utils.DateUtils;
import com.sjy.common.utils.StringUtils;
import com.sjy.common.utils.poi.ExcelUtil;
import com.sjy.framework.web.page.TableDataInfo;

@RestController
@Api(value = "亩均申诉相关接口", tags = {"亩均接口"})
@RequestMapping("/api/ent/appeal")
public class ApiEntAppealController extends BaseController
{
    @Autowired
    private IEntAppealService entAppealService;
    @Autowired
    private IEntAppealLandDataService landDataService;
    @Autowired
    private IEntAppealRentOutLandService rentOutLandService;
    @Autowired
    private IEntAppealRentInLandService rentInLandService;
    @Autowired
    private IEntKpiYearStaService kpiYearStaService;
	@Autowired
	private IUserService userService;
	@Autowired
	private IDeptService deptService;
    
    /**
     * 新增保存企业申诉 2022年7月9日16:39:51
     */
    @ApiOperation(value = "402、新增企业申诉", position = 402, notes = "")
    @Log(title = "企业申诉 ", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public ResponseEntity<BaseResponse> addSave(@RequestBody EntAppeal entAppeal)
    {
    	if(entAppeal!=null&&entAppeal.getDataYear()==null) {
    		entAppeal.setDataYear(DateUtil.thisYear()-1);
    	}
    	try {
    		//检测是否有重名CreditCode正在审核中
    		EntAppeal exist = entAppealService.selectEntAppealByCreditCode(entAppeal.getCreditCode(),entAppeal.getDataYear());
        	if(exist!=null) {
        		return BaseResponse.generateBadResponseEntity("新增失败-当前企业已存在待审批记录"+entAppeal.getId(), entAppeal);
        	}
        	System.out.println(com.alibaba.fastjson.JSONObject.toJSON(entAppeal));
        	SecuryUserDetail user = UserContext.getUserSession();
        	entAppeal.setCreateBy(user.getLoginName());
        	Date now = new Date();
        	//检测当前数据是否符合提交规范  规则后补
        	String validStr = validEntAppeal(entAppeal);
        	if(StringUtils.isNotBlank(validStr)) {
        		return BaseResponse.generateBadResponseEntity("操作失败:"+validStr, null);
        	}
        	int flag = entAppealService.insertEntAppeal(entAppeal);
        	if(flag>0) {
        		//老的自有产权证
        		if(entAppeal.getOldAppealLandDatas()!=null) {
        			entAppeal.getOldAppealLandDatas().forEach(n->{
        				n.setDataType(1);
        				n.setAppealId(entAppeal.getId());
	        			n.setKpiId(entAppeal.getKpiId());
	        			n.setCreateBy(user.getLoginName());
	        			n.setCreditCode(entAppeal.getCreditCode());
	        			landDataService.insertEntAppealLandData(n);
	        		});
        		}
        		//新的自有产权
        		if(entAppeal.getNewAppealLandDatas()!=null) {
        			entAppeal.getNewAppealLandDatas().forEach(n->{
        				n.setDataType(2);
        				n.setAppealId(entAppeal.getId());
	        			n.setKpiId(entAppeal.getKpiId());
	        			n.setCreateBy(user.getLoginName());
	        			n.setCreditCode(entAppeal.getCreditCode());
	        			landDataService.insertEntAppealLandData(n);
	        		});
        		}
        		//老的出租土地信息
        		if(entAppeal.getOldAppealRentInLands()!=null) {
        			entAppeal.getOldAppealRentInLands().forEach(n->{
		    			n.setId(null);
        				n.setDataType(1);
        				n.setAppealId(entAppeal.getId());
	        			n.setKpiId(entAppeal.getKpiId());
	        			n.setCreateBy(user.getLoginName());
	        			n.setDataYear(DateUtil.year(now)-1);
	        			n.setCreditCode(entAppeal.getCreditCode());
	        			rentInLandService.insertEntAppealRentInLand(n);
	        		});
        		}
        		//新的出租土地信息
        		if(entAppeal.getNewAppealRentInLands()!=null) {
        			entAppeal.getNewAppealRentInLands().forEach(n->{
		    			n.setId(null);
        				n.setDataType(2);
        				n.setAppealId(entAppeal.getId());
	        			n.setKpiId(entAppeal.getKpiId());
	        			n.setCreateBy(user.getLoginName());
	        			n.setDataYear(DateUtil.year(now)-1);
	        			n.setCreditCode(entAppeal.getCreditCode());
	        			rentInLandService.insertEntAppealRentInLand(n);
	        		});
        		}
        		//老的承租土地信息
        		if(entAppeal.getOldAppealRentOutLands()!=null) {
        			entAppeal.getOldAppealRentOutLands().forEach(n->{
		    			n.setId(null);
        				n.setDataType(1);
        				n.setAppealId(entAppeal.getId());
	        			n.setKpiId(entAppeal.getKpiId());
	        			n.setCreateBy(user.getLoginName());
	        			n.setDataYear(DateUtil.year(now)-1);
	        			n.setCreditCode(entAppeal.getCreditCode());
	        			rentOutLandService.insertEntAppealRentOutLand(n);
	        		});
        		}
        		//新的承租土地信息
        		if(entAppeal.getNewAppealRentOutLands()!=null) {
        			entAppeal.getNewAppealRentOutLands().forEach(n->{
		    			n.setId(null);
        				n.setDataType(2);
        				n.setAppealId(entAppeal.getId());
	        			n.setKpiId(entAppeal.getKpiId());
	        			n.setCreateBy(user.getLoginName());
	        			n.setDataYear(DateUtil.year(now)-1);
	        			n.setCreditCode(entAppeal.getCreditCode());
	        			rentOutLandService.insertEntAppealRentOutLand(n);
	        		});
        		}
        		return BaseResponse.generateOKResponseEntity("新增成功"); 
        	}
    		
	    	return BaseResponse.generateBadResponseEntity("新增失败", entAppeal);
		} catch (Exception e) {
			e.printStackTrace();
	        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	        return BaseResponse.generateBadResponseEntity("新增失败-数据格式异常"+e.getMessage(),null);
		}
    }
    
//    @Log(title = "企业申诉", businessType = BusinessType.DELETE)
//    @ApiOperation(value = "502、删除企业申诉信息", position = 502, notes = "英文半角逗号分割")
//    @ApiImplicitParams({
//	  @ApiImplicitParam(name = "ids", value = "id ,拼接字符串", required = false, example = "海城"),
//		 
//	 })
//    @PostMapping( "/remove")
//    public ResponseEntity<BaseResponse<String>> remove(String ids)
//    {
//    	int flag = entAppealService.deleteEntAppealByIds(ids);
//    	if(flag>0) {
//        	return BaseResponse.generateOKResponseEntity("删除成功"); 
//    	}
//        return BaseResponse.generateBadResponseEntity("删除失败", ids);
//    }
    
    /**
     * 修改保存企业申诉 2022年7月9日16:39:51
     */
    @ApiOperation(value = "403、修改企业申诉信息", position = 403, notes = "")
    @Log(title = "企业申诉 ", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public ResponseEntity<BaseResponse> editSave(EntAppeal entAppeal)
    {
    	if(entAppeal.getId()==null) {
        	return BaseResponse.generateBadResponseEntity("修改的时候Id不能为空", null);
    	}
    	EntAppeal oldData = entAppealService.selectEntAppealById(entAppeal.getId());
    	
        return null;
    }
    
    @ApiOperation(value = "404、企业申诉信息详情 包括kpi以及新老 产权、承租、出租", position = 404, notes = "")
    @PostMapping("/detailById")
    public ResponseEntity<BaseResponse<EntAppeal>> detailById(Long id)
    {
    	EntAppeal entAppeal = entAppealService.selectEntAppealById(id);
    	if(entAppeal != null && entAppeal.getId()!=null) {
    		//插入新老数据以及kpi数据
    		EntKpiYearSta entKpiYearSta = kpiYearStaService.getByCreditCodeAndYearWithList(entAppeal.getCreditCode(), entAppeal.getDataYear());
        	if(entKpiYearSta == null || entKpiYearSta.getConfirmFlag()!=1) {
        		return BaseResponse.generateBadResponseEntity("上报信息无效活未被确认",entKpiYearSta);
        	}
    		entAppeal.setKpi(entKpiYearSta);
    		
    		EntAppealLandData entAppealLandData = new EntAppealLandData();
    		entAppealLandData.setAppealId(id);
    		entAppealLandData.setDataType(1);
    		entAppeal.setOldAppealLandDatas(landDataService.selectEntAppealLandDataList(entAppealLandData));
    		entAppealLandData.setDataType(2);
    		entAppeal.setNewAppealLandDatas(landDataService.selectEntAppealLandDataList(entAppealLandData));

    		EntAppealRentInLand entAppealRentInLand = new EntAppealRentInLand();
    		entAppealRentInLand.setAppealId(id);
    		entAppealRentInLand.setDataType(1);
    		entAppeal.setOldAppealRentInLands(rentInLandService.selectEntAppealRentInLandList(entAppealRentInLand));
    		entAppealRentInLand.setDataType(2);
    		entAppeal.setNewAppealRentInLands(rentInLandService.selectEntAppealRentInLandList(entAppealRentInLand));

    		EntAppealRentOutLand entAppealRentOutLand = new EntAppealRentOutLand();
    		entAppealRentOutLand.setAppealId(id);
    		entAppealRentOutLand.setDataType(1);
    		entAppeal.setOldAppealRentOutLands(rentOutLandService.selectEntAppealRentOutLandList(entAppealRentOutLand));
    		entAppealRentOutLand.setDataType(2);
    		entAppeal.setNewAppealRentOutLands(rentOutLandService.selectEntAppealRentOutLandList(entAppealRentOutLand));
    		
        	return BaseResponse.generateOKResponseEntity(entAppeal);
    	}
    	
    	return BaseResponse.generateBadResponseEntity(500,"查询失败-记录不存在", entAppeal);
    }
    
    @ApiOperation(value = "405、根据统代跟年份查询 企业申诉信息详情 包括kpi以及新老 产权、承租、出租", position = 405, notes = "")
    @ApiImplicitParams({
		  @ApiImplicitParam(name = "dataYear", value = "年份", required = false, example = "1"),
		  @ApiImplicitParam(name = "creditCode", value = "统代", required = false, example = "1")
	  })
    @PostMapping("/detailByCreditCodeAndYear")
    public ResponseEntity<BaseResponse<EntAppeal>> detailByCreditCodeAndYear(Integer dataYear,String creditCode)
    {
    	EntAppeal entAppeal = entAppealService.selectEntAppealByCreditCode(creditCode,dataYear);
    	if(entAppeal != null && entAppeal.getId()!=null) {
    		//插入新老数据以及kpi数据
    		EntKpiYearSta entKpiYearSta = kpiYearStaService.getByCreditCodeAndYearWithList(entAppeal.getCreditCode(), entAppeal.getDataYear());
        	if(entKpiYearSta == null || entKpiYearSta.getConfirmFlag()!=1) {
        		return BaseResponse.generateBadResponseEntity("上报信息无效活未被确认",entKpiYearSta);
        	}
    		entAppeal.setKpi(entKpiYearSta);
    		
    		EntAppealLandData entAppealLandData = new EntAppealLandData();
    		entAppealLandData.setAppealId(entAppeal.getId());
    		entAppealLandData.setDataType(1);
    		entAppeal.setOldAppealLandDatas(landDataService.selectEntAppealLandDataList(entAppealLandData));
    		entAppealLandData.setDataType(2);
    		entAppeal.setNewAppealLandDatas(landDataService.selectEntAppealLandDataList(entAppealLandData));

    		EntAppealRentInLand entAppealRentInLand = new EntAppealRentInLand();
    		entAppealRentInLand.setAppealId(entAppeal.getId());
    		entAppealRentInLand.setDataType(1);
    		entAppeal.setOldAppealRentInLands(rentInLandService.selectEntAppealRentInLandList(entAppealRentInLand));
    		entAppealRentInLand.setDataType(2);
    		entAppeal.setNewAppealRentInLands(rentInLandService.selectEntAppealRentInLandList(entAppealRentInLand));

    		EntAppealRentOutLand entAppealRentOutLand = new EntAppealRentOutLand();
    		entAppealRentOutLand.setAppealId(entAppeal.getId());
    		entAppealRentOutLand.setDataType(1);
    		entAppeal.setOldAppealRentOutLands(rentOutLandService.selectEntAppealRentOutLandList(entAppealRentOutLand));
    		entAppealRentOutLand.setDataType(2);
    		entAppeal.setNewAppealRentOutLands(rentOutLandService.selectEntAppealRentOutLandList(entAppealRentOutLand));
    		
        	return BaseResponse.generateOKResponseEntity(entAppeal);
    	}
    	
    	return BaseResponse.generateBadResponseEntity(500,"查询失败-记录不存在", entAppeal);
    }
    
    @ApiOperation(value = "502、街道审批申诉信息", position = 502, notes = "status 1-待审核,2-审核通过,3-审核未通过")
    @ApiImplicitParams({
		  @ApiImplicitParam(name = "id", value = "申诉记录编号", required = false, example = "1"),
		  @ApiImplicitParam(name = "status", value = "审批状态 1-待审核,2-审核通过,3-审核未通过", required = false, example = "1"),
		  @ApiImplicitParam(name = "aprovalContent", value = "审批内容，不通过必填；通过选填", required = false, example = "1")
	  })
    @PostMapping("/approvalByStreet")
    public ResponseEntity<BaseResponse<EntAppeal>> approvalByStreet(Long id,Integer status,String aprovalContent)
    {
    	EntAppeal entAppeal = entAppealService.selectEntAppealById(id);
    	//判断权限，是否是街道
    	SecuryUserDetail user1 = UserContext.getUserSession();
    	User user = userService.selectUserById(user1.getUserId());
    	if(!"00".equals(user.getUserType())||!user.getDept().getDeptName().equals(entAppeal.getTown())) {
    		return BaseResponse.generateBadResponseEntity("无权修改-当前账号非企业对应街道账号", null);
    	}
    	
    	
    	if(entAppeal == null || entAppeal.getId()==null) {
        	return BaseResponse.generateBadResponseEntity("审批失败:记录不存在",null);
    	}
    	if(entAppeal.getAppealStatus() != 1) {//审批状态 1-待审核,2-审核通过,3-审核未通过
    		return BaseResponse.generateBadResponseEntity("审批失败:记录已经在"+DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", entAppeal.getApprovalTime())+"被"+AppealEnum.getName(entAppeal.getAppealStatus()),entAppeal);
    	}
    	
    	return BaseResponse.generateOKResponseEntity("审批成功", entAppeal);
    }
    
    private String validEntAppeal(EntAppeal entAppeal) {
    	return null;
    }
}
